package com.chuanzhi.recyclingmall.common.advice;

import com.chuanzhi.recyclingmall.common.exception.BizException;
import com.chuanzhi.recyclingmall.common.result.Result;
import com.chuanzhi.recyclingmall.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 * @author lihui
 * @version 1.0
 * @date 2023/2/19 17:10
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * <p> 自定义异常 </p>
     *
     * @param req
     * @param e
     * @return: com.chuanzhi.recyclingmall.common.result.Result
     * @author lihui
     * @date: 2023/2/19 17:45
     */
    @ResponseBody
    @ExceptionHandler(value =BizException.class)
    public Result exceptionHandler(HttpServletRequest req, BizException e){
        log.error("业务异常！原因是:",e);
        return Result.failed(ResultCode.BIZ_OTHER_ERROR.getCode(), ResultCode.BIZ_OTHER_ERROR.getMessage());
    }

    /**
     * <p> 处理空指针的异常 </p>
     *
     * @param req
     * @param e
     * @return: com.chuanzhi.recyclingmall.common.result.Result
     * @author lihui
     * @date: 2023/2/19 17:46
     */
    @ResponseBody
    @ExceptionHandler(value =NullPointerException.class)
    public Result exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        return Result.failed(ResultCode.NULL_POINT_ERROR.getCode(), ResultCode.NULL_POINT_ERROR.getMessage());
    }

    /**
     * <p> 处理其他异常 </p>
     *
     * @param req
     * @param e
     * @return: com.chuanzhi.recyclingmall.common.result.Result
     * @author lihui
     * @date: 2023/2/19 17:46
     */
    @ResponseBody
    @ExceptionHandler(value =Exception.class)
    public Result exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:",e);
        return Result.failed(ResultCode.FAILURE.getCode(), ResultCode.FAILURE.getMessage());
    }
}
